package com.yx.cloud.product.laser.yxcloud;

import android.content.Context;
import android.graphics.Color;

import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;
import com.iot.product.sweeper.bean.BaseStation;
import com.iot.product.sweeper.bean.Robot;
import com.iot.sweeper.param.BaseStationSettingParam;
import com.iot.sweeper.param.CleanSettingParam;
import com.yx.cloud.R;
import com.yx.cloud.product.ProductConfigConstants;
import com.yx.cloud.product.laser.tuyapublic.TuyaLaserConstant;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

public class U3_FULL extends X3_YXCLOUD {
    public static final String PID = "u3-full";
    public static final String PNAME = "U3 Pro";

    public static final String DP_LIGHT = "136";
    public static final String DP_AIRCLEANER_SWITCH = "140";
    public static final String DP_AIRCLEANER = "142";
    public static final String DP_AIRCLEANER_RESET_STANDARD_LIFE = "144";
    public static final String DP_AIRCLEANER_RESET_HCHO_LIFE = "146";

    private U3_FULL() {
        setProductId(PID);
        getProduct().setProductName(PNAME);
        getProduct().setProductIcon(R.mipmap.robot_icon_u3pro);
    }

    @Override
    public void setDeviceId(String deviceId) {
        super.setDeviceId(deviceId);
        try {
            //因为机器设置的风格图片是通过deviceid做key的  在创建对象初始化配置时还没有设置deviceid 所以在这里设置
            product.getConfigureMap().put(ProductConfigConstants.robot_Airview, R.mipmap.main_u3pro_icon);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void initConfig() {
        super.initConfig();
        //TODO 后续考虑从文件中读取
        U3FULLConfig.initConfig(getProduct().getConfigureMap(), this);
    }

    @Override
    public void parseDp(JSONObject dataJson) throws JSONException {
        super.parseDp(dataJson);
        JSONObject jsonObject = dataJson.getJSONObject("thing_status");
        YxCloudLaserDataConverter.parseDp(this, jsonObject);
        initRobotData(this, jsonObject);
    }

    private void initRobotData(Robot robot, JSONObject jsonObject) {
        try {
            if (jsonObject.has(TuyaLaserConstant.WORK_MODE)) {
                //清扫模式 both_work - 扫拖模式
                //only_sweep - 只扫模式
                //only_mop - 只拖模式
//                String mode = "";
                int workMode = jsonObject.getInt(TuyaLaserConstant.WORK_MODE);
                robot.getCleanSettings().setWorkMode(workMode);
                Event.newBuilder().type(Event.MESSAGE_TYPE_CLEAN_MODE).send();
            }
            if (jsonObject.has(TuyaLaserConstant.UNIT_SET)) {
                //单位设置
                int unitSettings = jsonObject.getInt(TuyaLaserConstant.UNIT_SET);
                robot.getCleanSettings().setUnitSettings(unitSettings);
                Event.newBuilder().type(Event.MESSAGE_TYPE_UNIT_AREA).content(unitSettings).send();//和童锁使用同??
            }
            if (jsonObject.has(TuyaLaserConstant.CHILD_LOCK)) {
                //童锁
                boolean childLock = jsonObject.getBoolean(TuyaLaserConstant.CHILD_LOCK);
                robot.getCleanSettings().setChildLock(childLock);
                Event.newBuilder().type(Event.MESSAGE_TYPE_CHILD_LOCK).content(childLock).send();
            }
            if (jsonObject.has(TuyaLaserConstant.CARPET_CLEAN_PREFER)) {
                /*地毯清洁偏好 adaptive - 智能上毯 evade - 自动避毯*/
                int carpetSettingPreference = jsonObject.getInt(TuyaLaserConstant.CARPET_CLEAN_PREFER);
                robot.getCleanSettings().setCarpetSetting(carpetSettingPreference);
            }
            if (jsonObject.has(TuyaLaserConstant.CLEAN_MOP)) {
                //立即清洗拖布
                boolean cleanMop = jsonObject.getBoolean(TuyaLaserConstant.CLEAN_MOP);
                robot.getCleanSettings().setCleanMop(cleanMop);
                Event.newBuilder().result(true).type(Event.MESSAGE_TYPE_CLEAN_MOP).content(cleanMop).send();
            }
            if (jsonObject.has(TuyaLaserConstant.DUST_COLLECTION_NUM)) {
                /*集尘频率设置 0 - 关闭自动集尘 1 - 1? 2 - 2? 3 - 3?*/
                int dust_collection_num = jsonObject.getInt(TuyaLaserConstant.DUST_COLLECTION_NUM);
                robot.getCleanSettings().setAutoDust(dust_collection_num + "");
                Event.newBuilder().type(Event.MESSAGE_TYPE_DUST_COLLECTION_NUM).content(dust_collection_num).send();
            }
            if (jsonObject.has(TuyaLaserConstant.CLEANING_FREQUENCY)) {
                //回洗频率
                int frequenc = 30;
                int fre = jsonObject.getInt(TuyaLaserConstant.CLEANING_FREQUENCY);
                if (fre == 0) {
                    frequenc = 30;
                } else if (fre == 1) {
                    frequenc = 20;
                } else if (fre == 2) {
                    frequenc = 10;
                }
                robot.getCleanSettings().setBackwashFrequency(frequenc);
                Event.newBuilder().result(true).type(Event.MSG_ROBOT_SETTINGS).content(frequenc).send();
            }
            if (jsonObject.has(TuyaLaserConstant.AUTO_DRY)) {
                //自动风干开关
                boolean drySwitch = jsonObject.getBoolean(TuyaLaserConstant.AUTO_DRY);
                robot.getCleanSettings().setDrySwitch(drySwitch);
                Event.newBuilder().type(Event.MESSAGE_TYPE_DRY_SWITCH).content(drySwitch).send();
            }
            if (jsonObject.has(TuyaLaserConstant.HAND_DRY)) {
                //立即风干
                boolean dryState = jsonObject.getBoolean(TuyaLaserConstant.HAND_DRY);
                robot.getCleanSettings().setDryState(dryState);
                Event.newBuilder().result(true).type(Event.MESSAGE_TYPE_DRY_STATE).content(dryState).send();
            }
            if (jsonObject.has(TuyaLaserConstant.DUST_COLLECTION_DURATION)) {
                //集尘时长
                String dustTime = jsonObject.getString(TuyaLaserConstant.DUST_COLLECTION_DURATION);
                robot.getCleanSettings().setDustTime(dustTime);
                Event.newBuilder().type(Event.MESSAGE_TYPE_DUST_COLLECTION).result(true).send();
            }
            if (jsonObject.has(TuyaLaserConstant.AUTO_MOISTURIZING)) {
                //自动 补水
                boolean auto_water = jsonObject.getBoolean("154");
            }
            if (jsonObject.has(TuyaLaserConstant.CLEANING_MOP_TIMES)) {
                //清洗拖布次数
                int cleanMopFrequency = jsonObject.getInt(TuyaLaserConstant.CLEANING_MOP_TIMES);
                robot.getCleanSettings().setCleanMopFrequency(cleanMopFrequency);
                Event.newBuilder().type(Event.MESSAGE_TYPE_CLEAN_MOP_FREQUENCY).content(cleanMopFrequency).send();
            }
            if (jsonObject.has(TuyaLaserConstant.DRYING_TIME)) {
                //烘干时间
                int dryingTime = jsonObject.getInt(TuyaLaserConstant.DRYING_TIME);
                String mDryingTime = "";
                if (dryingTime == 0) {
                    mDryingTime = "low";
                } else if (dryingTime == 1) {
                    mDryingTime = "middle";
                } else if (dryingTime == 2) {
                    mDryingTime = "high";
                }
                robot.getCleanSettings().setDryingTime(mDryingTime);
                Event.newBuilder().type(Event.MESSAGE_TYPE_DRYING_TIME).content(dryingTime).send();
            }
            if (jsonObject.has(TuyaLaserConstant.AI_OBSTACLE_AVOIDANCE_SWITCH)) {
                //AI避障
                boolean aiAvoidanceSwitch = jsonObject.getBoolean(TuyaLaserConstant.AI_OBSTACLE_AVOIDANCE_SWITCH);
                robot.getCameraSettings().setAiAvoidanceSwitch(aiAvoidanceSwitch);
            }
            if (jsonObject.has(TuyaLaserConstant.HOME_ENVIRONMENT_IDENTIFICATION_SWITCH)) {
                //家居识别
                boolean homeEnvironmentRecognitionSwitch = jsonObject.getBoolean(TuyaLaserConstant.HOME_ENVIRONMENT_IDENTIFICATION_SWITCH);
                robot.getCameraSettings().setHomeEnvironmentRecognitionSwitch(homeEnvironmentRecognitionSwitch);
            }
            if (jsonObject.has(TuyaLaserConstant.VIDEO_SWITCH)) {
                //实时视频开关
                boolean liveVideoSwitch = jsonObject.getBoolean(TuyaLaserConstant.VIDEO_SWITCH);
                robot.getCameraSettings().setLiveVideoSwitch(liveVideoSwitch);
            }
            if (jsonObject.has(TuyaLaserConstant.VIDEO_REMINDER_SWITCH)) {
                //视频提醒开关
                boolean videoReminder = jsonObject.getBoolean(TuyaLaserConstant.VIDEO_REMINDER_SWITCH);
                robot.getCameraSettings().setVideoReminderSwitch(videoReminder);
            }
            if (jsonObject.has(TuyaLaserConstant.BASE_WATERTANK_STATUS)) {
                //基站状态 0-清水箱正常 1-清水箱缺水 2-清水箱未安装 3-尘袋正常 4-尘袋已满 5-尘袋未安装 6-污水箱正常 7-污水箱已满 8-污水箱未安装
                String base_station_status = jsonObject.getString(TuyaLaserConstant.BASE_WATERTANK_STATUS);
                robot.getCleanSettings().setBaseStationStatus(base_station_status);
                Event.newBuilder().result(true).type(Event.MESSAGE_TYPE_BASE_WATERTANK_STATUS).content(base_station_status).send();
            }
            if (jsonObject.has(TuyaLaserConstant.SELF_CLEANING)) {
                //自清洁 true：：返回自清洁； false：取消返回
                boolean self_cleaning = jsonObject.getBoolean(TuyaLaserConstant.SELF_CLEANING);
                robot.getCleanSettings().setSelfCleaning(self_cleaning);
                Event.newBuilder().result(true).type(Event.MESSAGE_TYPE_SELF_CLEANING).content(self_cleaning).send();
            }
            if (jsonObject.has(TuyaLaserConstant.ON_THE_CARPET)) {
                //在地毯上
                boolean onCarpet = jsonObject.getBoolean(TuyaLaserConstant.ON_THE_CARPET);
                robot.getCameraSettings().setOnCarpet(onCarpet);
            }
            if (jsonObject.has(DP_LIGHT)) {
                //基站灯光开关
                String lightStr = jsonObject.getString(DP_LIGHT);
                parseLightCmd(baseStation, lightStr);
                Event.newBuilder().type(Event.MEG_ROBOT_BASESTATION_LIGHT).content(baseStation).result(true).send();
            }
            if (jsonObject.has(DP_AIRCLEANER_SWITCH)) {
                //空气净化器开关
                int airCleanState = jsonObject.getInt(DP_AIRCLEANER_SWITCH);
                if (0 == airCleanState) {
                    baseStation.setAirCleanerSwitch(false);
                    baseStation.setPlasmaSwitch(false);
                } else if (1 == airCleanState) {
                    baseStation.setAirCleanerSwitch(true);
                    baseStation.setPlasmaSwitch(true);
                } else if (2 == airCleanState) {
                    baseStation.setAirCleanerSwitch(true);
                    baseStation.setPlasmaSwitch(false);
                }
                Event.newBuilder().type(Event.MEG_ROBOT_BASESTATION_AIRCLEAN).content(baseStation).result(true).send();
            }
            if (jsonObject.has(DP_AIRCLEANER)) {
                //空气净化器档位
                int airStation = jsonObject.getInt(DP_AIRCLEANER);
                baseStation.setAirCleaner(airStation);
                Event.newBuilder().type(Event.MEG_ROBOT_BASESTATION_AIRCLEAN).content(baseStation).result(true).send();
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public void setDeviceCleanSettings(CleanSettingParam param) {
        LogUtils.i("U3 Pro......setCleanSettings  ");
        //音量
        if (param.hasset_volume) {
            sendToDevice(TuyaLaserConstant.VOLUME_SET, param.getVolume());
        }
        //断点续扫
        if (param.hasset_breakpointResume) {
            sendToDevice(TuyaLaserConstant.BREAK_CLEAN, param.isBreakpointResume());
        }
        if (param.hasset_unitSettings) {
            //单位设置
            sendToDevice(TuyaLaserConstant.UNIT_SET, param.getUnitSettings());
        }
        //童锁
        if (param.hasset_childLock) {
            sendToDevice(TuyaLaserConstant.CHILD_LOCK, param.isChildLock());
        }

        //清扫模式41
        if (param.hasset_workMode) {
            sendToDevice(TuyaLaserConstant.WORK_MODE, param.getWorkMode());
        }

        //地毯设置44
        if (param.hasset_carpetSetting) {
            sendToDevice(TuyaLaserConstant.CARPET_CLEAN_PREFER, param.getCarpetSetting());
        }

        //清扫拖布
        if (param.hasset_cleanMop) {
            sendToDevice(TuyaLaserConstant.CLEAN_MOP, param.isCleanMop());
        }
        //回洗频率
        if (param.hasset_backwashFrequency) {
            int frequency = param.getBackwashFrequency();
            int sFrequency = 0;
            if (frequency == 10) {
                sFrequency = 2;
            } else if (frequency == 20) {
                sFrequency = 1;
            } else if (frequency == 30) {
                sFrequency = 0;
            }
            sendToDevice(TuyaLaserConstant.CLEANING_FREQUENCY, sFrequency);
        }
        //自动集尘开关/频率
        if (param.hasset_autoDust_frequency) {
            sendToDevice(TuyaLaserConstant.DUST_COLLECTION_NUM, param.getAutoDustFrequency());
        }
        //立即集尘
        if (param.hasset_autoDust) {
            sendToDevice(TuyaLaserConstant.DUST_COLLECTION_SWITCH, param.isAutoDust());
        }
        //自动风干
        if (param.hasset_drySwitch) {
            sendToDevice(TuyaLaserConstant.AUTO_DRY, param.isDrySwitch());
        }
        //立即风干
        if (param.hasset_dryState) {
            sendToDevice(TuyaLaserConstant.HAND_DRY, param.isDryState());
        }
        if (param.hasset_dustTime) {
            //集尘时长
            sendToDevice(TuyaLaserConstant.DUST_COLLECTION_DURATION, param.getDustTime());
        }
        //清洗拖布次数
        if (param.hasset_cleanMopFrequency) {
            sendToDevice(TuyaLaserConstant.CLEANING_MOP_TIMES, param.getCleanMopFrequency());
        }
        //烘干时间
        if (param.hasset_dryingTime) {
            String dryingTime = param.getDryingTime();
            int mDryingTime = 0;
            if (dryingTime.equals("low")) {
                mDryingTime = 0;
            } else if (dryingTime.equals("middle")) {
                mDryingTime = 1;
            } else if (dryingTime.equals("high")) {
                mDryingTime = 2;
            }
            sendToDevice(TuyaLaserConstant.DRYING_TIME, mDryingTime);
        }
        //AI 避障
        if (param.hasset_aiAvoidanceSwitch) {
            sendToDevice(TuyaLaserConstant.AI_OBSTACLE_AVOIDANCE_SWITCH, param.isAiAvoidanceSwitch());
        }
        //家居环境识别开关
        if (param.hasset_homeEnvironmentRecognitionSwitch) {
            sendToDevice(TuyaLaserConstant.HOME_ENVIRONMENT_IDENTIFICATION_SWITCH, param.isHomeEnvironmentRecognitionSwitch());
        }
        //实时视频开关
        if (param.hasset_liveVideoSwitch) {
            sendToDevice(TuyaLaserConstant.VIDEO_SWITCH, param.isLiveVideoSwitch());
        }
        //视频提醒开关
        if (param.hasset_videoReminderSwitch) {
            sendToDevice(TuyaLaserConstant.VIDEO_REMINDER_SWITCH, param.isVideoReminderSwitch());
        }
        //自清洁
        if (param.hasset_selfCleaning) {
            sendToDevice(TuyaLaserConstant.SELF_CLEANING, param.isSelfCleaning());
        }
    }

    @Override
    public void setBaseStationSetting(BaseStationSettingParam param) {
        //基站灯光
        if (param.isHasset_light()) {
            String cmd = getLightCmd(param);
            sendToDevice(DP_LIGHT, cmd);
        }
        //基站空气净化器-开关
        if (param.isHasset_airCleanerSwitch() && param.isHasset_plasmaSwitch()) {
            if (param.getAirCleanerSwitch()) {
                if (param.isPlasmaSwitch()) {
                    sendToDevice(DP_AIRCLEANER_SWITCH, 1);
                } else {
                    sendToDevice(DP_AIRCLEANER_SWITCH, 2);
                }
            } else {
                sendToDevice(DP_AIRCLEANER_SWITCH, 0);
            }
        }
        //基站空气净化器档位
        if (param.isHasset_airCleaner()) {
            sendToDevice(DP_AIRCLEANER, param.getAirCleaner());
        }

        if (param.isHasset_resetFilter()) {
            if (param.getResetFilterType() == BaseStation.AIR_FILTER_HCHO) {
                sendToDevice(DP_AIRCLEANER_RESET_HCHO_LIFE, true);
            } else {
                sendToDevice(DP_AIRCLEANER_RESET_STANDARD_LIFE, true);
            }
        }
    }

    @Override
    public void setLightControls(boolean lightSwitch) {
        //灯光
        sendToDevice(TuyaLaserConstant.LIGHT_SWITCH, lightSwitch);
    }

    public void parseLightCmd(BaseStation baseStation, String cmd) {
        if (cmd.length() == 10) {
            try {
                int switcher = Integer.parseInt(cmd.substring(0, 2), 16);
//                int color = Integer.parseInt("FF" + cmd.substring(2, 8),16);
                int color = Color.parseColor("#ff" + cmd.substring(2, 8));
                int brightness = Integer.parseInt(cmd.substring(8), 16);
                baseStation.setLightSwitch(switcher != 0);
                if (switcher == 2) {
                    baseStation.setLightType(BaseStation.LIGHT_TYPE_COLORFUL);
                } else if (switcher == 3) {
                    baseStation.setLightType(BaseStation.LIGHT_TYPE_RAINBOW);
                } else {
                    baseStation.setLightType(BaseStation.LIGHT_TYPE_WHITE);
                }
                baseStation.setLightColor(color);
                baseStation.setBrightness(brightness);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
    }

    private String getLightCmd(BaseStationSettingParam param) {

        int switcher;
        if (param.getLightSwitch()) {
            if (param.getLightType() == BaseStation.LIGHT_TYPE_COLORFUL) {
                switcher = 2;
            } else if (param.getLightType() == BaseStation.LIGHT_TYPE_RAINBOW) {
                switcher = 3;
            } else {
                switcher = 1;
            }
        } else {
            switcher = 0;
        }

        int rgb = param.getLightColor();
        int r = (rgb & 0x00ff0000) >> 16;
        int g = (rgb & 0x0000ff00) >> 8;
        int b = rgb & 0x000000ff;

        String cmd = getHex(switcher) + getHex(r) + getHex(g) + getHex(b) + getHex(param.getBrightness());
        return cmd;
    }

    private String getHex(int i) {
        return i < 16 ? "0" + Integer.toHexString(i) : Integer.toHexString(i);
    }

    @Override
    public String getFaultMsgByCode(Context context, String faltCode) {
        int srrCode = Integer.parseInt(faltCode);
//        int errCode = getFaultCode(srrCode - 1);
        String errType = "";
        String errDetail = "";
        switch (srrCode) {
            case 1:
                errType = context.getResources().getString(R.string.U_Err_1);
                break;
            case 2:
                errType = context.getResources().getString(R.string.U_Err_2);
                break;
            case 3:
                errType = context.getResources().getString(R.string.U_Err_3);
                break;
            case 4:
                errType = context.getResources().getString(R.string.U_Err_4);
                break;
            case 5:
                errType = context.getResources().getString(R.string.U_Err_5);
                break;
            case 6:
                errType = context.getResources().getString(R.string.U_Err_6);
                break;
            case 7:
                errType = context.getResources().getString(R.string.U_Err_7);
                break;
            case 8:
                errType = context.getResources().getString(R.string.U_Err_8);
                break;
            case 9:
                errType = context.getResources().getString(R.string.U_Err_9);
                break;
            case 10:
                errType = context.getResources().getString(R.string.U_Err_10_A);
                break;
            case 11:
                errType = context.getResources().getString(R.string.U_Err_11);
                break;
            case 12:
                errType = context.getResources().getString(R.string.U_Err_12);
                break;
            case 13:
                errType = context.getResources().getString(R.string.U_Err_13);
                break;
            case 14:
                errType = context.getResources().getString(R.string.U_Err_14);
                break;
            case 15:
                errType = context.getResources().getString(R.string.U_Err_15);
                break;
            case 16:
                errType = context.getResources().getString(R.string.U_Err_16);
                break;
            case 17:
                errType = context.getResources().getString(R.string.U_Err_17);
                break;
            case 18:
                errType = context.getResources().getString(R.string.U_Err_18);
                break;
            case 19:
                errType = context.getResources().getString(R.string.U_Err_19);
                break;
            case 20:
                errType = context.getResources().getString(R.string.U_Err_20);
                break;
            case 21:
                errType = context.getResources().getString(R.string.U_Err_21);
                break;
            case 22:
                errType = context.getResources().getString(R.string.U_Err_22);
                break;
            case 23:
                errType = context.getResources().getString(R.string.U_Err_23);
                break;
            case 24:
                errType = context.getResources().getString(R.string.U_Err_24);
                break;
            case 25:
                errType = context.getResources().getString(R.string.U_Err_25);
                break;
            case 26:
                errType = context.getResources().getString(R.string.U_Err_26);
                break;
            case 27:
                errType = context.getResources().getString(R.string.U_Err_27);
                break;
            case 28:
                errType = context.getResources().getString(R.string.U_Err_28);
                break;
            case 29:
                errType = context.getResources().getString(R.string.U_Err_29_A);
                break;

        }
        return errType;
    }
}
